package org.example.eatback.service.Impl;

import org.example.eatback.mappers.DiaryMapper;
import org.example.eatback.pojo.DiaryRecord;
import org.example.eatback.service.DiaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

@Service
public class DiaryServiceImpl implements DiaryService {

    @Autowired
    private DiaryMapper diaryMapper;


    public DiaryRecord getDailyRecord(String username, LocalDate date) {
        DiaryRecord record = diaryMapper.findByUsernameAndDate(username, date);
        if (record == null) {
            record = new DiaryRecord();
            record.setUsername(username);
            record.setRecordDate(date);
            record.setWater(0);
            record.setCalories(0);
            record.setWeight(0.0);
            record.setBreakfastCalories(0);
            record.setLunchCalories(0);
            record.setDinnerCalories(0);
        }
        return record;
    }

    public void updateMeal(String username, LocalDate date, String mealType,
                           String foods, Integer calories, String notes) {
        DiaryRecord existing = diaryMapper.findByUsernameAndDate(username, date);
        if (existing == null) {
            // 如果当天记录不存在，先创建一条记录
            DiaryRecord newRecord = new DiaryRecord();
            newRecord.setUsername(username);
            newRecord.setRecordDate(date);
            newRecord.setWater(0);
            newRecord.setCalories(0);
            newRecord.setWeight(0.0);
            diaryMapper.insert(newRecord);
        }

        // 更新对应餐次的数据
        diaryMapper.updateMeal(username, date, mealType.toLowerCase(), foods, calories, notes);
    }


    public void saveOrUpdate(DiaryRecord record) {
        DiaryRecord existing = diaryMapper.findByUsernameAndDate(
                record.getUsername(),
                record.getRecordDate()
        );

        if (existing == null) {
            diaryMapper.insert(record);
        } else {
            diaryMapper.update(record);
        }
    }

    public void deleteMeal(String username, LocalDate date, String mealType) {
        DiaryRecord existing = diaryMapper.findByUsernameAndDate(username, date);
        if (existing != null) {
            // 更新对应餐次的数据为空
            diaryMapper.deleteMeal(username, date, mealType.toLowerCase());
        }
    }
}
